<?php

namespace app\service;


use app\common\model\PrivateChatHistoryModel;
use app\common\model\PrivateChatSessionModel;
use app\common\model\UserModel;
use think\facade\Cache;

class GroupchatService extends Service
{
    public function __construct()
    {
        parent::__construct();
    }

    /**
     * 获取主播列表
     * @param $admin_role
     * @param $admin_id
     * @param $search_name 搜索主播id和昵称
     * @return array
     */
    static public function getAnchorList($admin_role, $admin_id, $search_name = '')
    {
        $where = [
            'is_anchor=1',
            'status=0',
        ];

        // 权限判断
        if ($admin_role != 1 && $admin_role != 11) {
            $user_ids = self::getChatUserIds($admin_id);
            if ($user_ids) {
                $user_ids = implode(',', $user_ids);
                $where[]  = "id IN($user_ids)";
            } else {
                // 如果没有设置私聊用户
                return [];
            }
        }

        if ($search_name) {
            $where[] = "(id LIKE '%$search_name%' OR nick_name LIKE '%$search_name%')";
        }

        $where = implode(' AND ', $where);

        // 主播列表
        $anchor_list = UserModel::field('id,nick_name,avatar')->withCount([
            'gchat' => function ($query) {
                $query->where('status', 0)->field('id');
            }
        ])->where($where)
            ->order('id DESC')
            ->select();

        return $anchor_list;
    }

    /**
     * 获取私聊用户id
     * @param $admin_id
     * @return array
     */
    static public function getChatUserIds($admin_id)
    {
        return UserModel::where("FIND_IN_SET($admin_id,chat_admin_ids)")->column('id');
    }

    /**
     * 检测admin账号是否有权限跟用户私聊
     * @param $admin_role
     * @param $admin_id
     * @param $anchor_id 主播id
     * @return array
     */
    static public function checkAdminChat($admin_role, $admin_id, $anchor_id)
    {
        // 权限判断
        if ($admin_role != 1 && $admin_role != 11) {
            $chat_admin_ids = explode(',', UserModel::where('id', $anchor_id)->value('chat_admin_ids'));
            if (!$chat_admin_ids || !in_array($admin_id, $chat_admin_ids)) {
                return parent::returnData(1, '你当前没有权限回复该用户聊天');
            }
        }
        return parent::returnData();
    }


}